<?php
class Admin_AdvertisementController extends Zendhlt_Controller_AdminAction {

	const ADD_PAGE_TITLE = 'Thêm thông tin quảng cáo';
	const LIST_PAGE_TITLE = 'Danh sách quảng cáo';
	const EDIT_PAGE_TITLE = 'Chỉnh sửa thông tin quảng cáo';
	const ACTIVE = 1;
	
	private $_currentUser;
	private $_arrParam;
	private $_paginator = array();
	private $_actionMain;
	private $_namespace;
	
	public function init() {
		$layoutPath = TEMPLATE_PATH . '/admin';
		$option = array('layout'     => 'index',
                   		'layoutPath' => $layoutPath);
		Zend_Layout::startMvc($option);

		// Phân trang
		$this->_paginator['itemCountPerPage'] = 5;
		$this->_paginator['pageRange'] 		  = 3;
		$this->_paginator['currentPage'] 	  = $this->_request->getParam('page', 1);

		// Mang tham so nhan duoc o moi Action
		$this->_arrParam = $this->_request->getParams();

		// Duong dan cua Action chinh
		$this->_actionMain = '/' . $this->_arrParam['module'] . '/' . $this->_arrParam['controller'];

		// Dat ten SESSION
		// Luu cac du lieu filter vao SESSION
		$this->_namespace = $this->_arrParam['module'] . '-' . $this->_arrParam['controller'];
		$ssFilter = new Zend_Session_Namespace($this->_namespace);

		if(empty($ssFilter->col) || ($this->_request->getParam('resetfilter', 0) == 1)) {
			$ssFilter->keywords 	= '';
			$ssFilter->col 			= 'ngay_tao';
			$ssFilter->order 		= 'DESC';
			$ssFilter->state 		= self::ACTIVE;
			$ssFilter->error 		= 0;
		}

		$this->_arrParam['paginator']			 = $this->_paginator;
		$this->_arrParam['ssFilter']['keywords'] = $ssFilter->keywords;
		$this->_arrParam['ssFilter']['col'] 	 = $ssFilter->col;
		$this->_arrParam['ssFilter']['order'] 	 = $ssFilter->order;
		$this->_arrParam['ssFilter']['state'] 	 = $ssFilter->state;

		// Truyen ra view
		$this->view->actionMain = $this->_actionMain;
		$this->view->currentController = '/' . $this->_arrParam['module'] . '/' . $this->_arrParam['controller'];
		$this->view->arrParam = $this->_arrParam;

		// Lay thong tin user admin hien tai
		$auth = Zend_Auth::getInstance();
		$this->_currentUser = $auth->getIdentity();
	}
	
	public function indexAction() {
		$this->view->headTitle(self::LIST_PAGE_TITLE);
		
		$model = new Admin_Model_AdvertisementMapper();
		$paginator = new Zendhlt_Paginator();

		$advs = $model->fetch($this->_arrParam);
		$totalItem = $model->countItem($this->_arrParam);

		$this->view->panigator = $paginator->createPaginator($totalItem, $this->_paginator);
		$this->view->totalItems = $totalItem;
		$this->view->Items = $advs;
		
		// Display error if delete occur error {
		$ssFilter = new Zend_Session_Namespace($this->_namespace);
		$this->view->msg = '';
		
		if ($ssFilter->error == 1) {
			$this->view->msg = 'Xuất hiện lổi trong quá trình thực hiện!';
			$ssFilter->error = 0;
		}
		// }
	}
	
	private function checkImageSize($image, $position) {
		$image_info = getimagesize($image);
		$image_width = $image_info[0];
		$image_height = $image_info[1];
		
		switch($position) {
			case '1':
				if($image_width > 486 || $image_height > 99) {
					return '(486 x 99)';
				}
				break;
			case '2':
				if($image_width > 150) {
					return '(150 x )';
				}
				break;
			case '3':
				if($image_width > 639 || $image_height > 296) {
					return '(639 x 296)';
				}
				break;
			case '4':
				if($image_width > 150) {
					return '(150 x )';
				}
				break;
			case '5':
				break;
			case '6':
				break;
		}
		
		return '';
	}
	
	public function addAction() {
		$this->view->headTitle(self::ADD_PAGE_TITLE);

		$form = new Admin_Form_Advertisement();
		$this->view->form = $form;
		$this->view->msg = '';
		
		$model = new Admin_Model_PageMapper();
		$pages = $model->fetchAll(null);
		foreach ($pages as $value) {
			$form->page_id->addMultiOption($value->getId(), $value->getPage());
		}
		
		$model = new Admin_Model_PositionMapper();
		$positions = $model->fetchAll(null);
		foreach ($positions as $value) {
			$form->vi_tri->addMultiOption($value->getId(), $value->getPosition());
		}
		
		$model = new Admin_Model_CustomerMapper();
		$customers = $model->fetchAll('trang_thai=1', 'view');
		foreach ($customers as $value) {
			$form->id_khach_hang->addMultiOption($value->getId(), $value->getTen_khach_hang());
		}
		
		$model = new Admin_Model_AdpackageMapper();
		$advPackages = $model->fetchAll('trang_thai=1', 'view');
		foreach ($advPackages as $value) {
			$form->id_goi_quang_cao->addMultiOption($value->getId(), $value->getTen_goi());
		}
		
		$form->uu_tien->setValue("0");
		$form->image_url->setRequired(true);
		$form->ngay_het_han->setValue(date("d-m-Y", mktime(0, 0, 0, date("m") + 1, date("d"), date("Y"))));
		$model = new Admin_Model_AdvertisementMapper();
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();

			if ($form->isValid($formData)) {
				$checkImage = $this->checkImageSize($_FILES['image_url']['tmp_name'], $form->getValue('vi_tri'));
				
				if($checkImage == '') {
					$upload = new Zendhlt_File_Upload();
					$newFileName = $upload->upload('image_url', ADV_IMAGES_PATH, array('task' => 'rename'));
					
					$currentDate = date('Y-m-d H:i:s');
					$advertisement = new Admin_Model_TableColumn_Advertisement($formData);
					$advertisement->setId(0);
					$advertisement->setImage_url($newFileName);
					$advertisement->setNgay_het_han(date_format(date_create_from_format('d-m-Y', $form->getValue('ngay_het_han')), 'Y-m-d'));
					$advertisement->setNguoi_tao($this->_currentUser->id);
					$advertisement->setNgay_tao($currentDate);
					$advertisement->setNguoi_cap_nhat($this->_currentUser->id);
					$advertisement->setNgay_cap_nhat($currentDate);
					$advertisement->setTrang_thai(self::ACTIVE);
					
					if ($model->save($advertisement)) {
						$form->reset();
						$form->uu_tien->setValue("0");
						$form->ngay_het_han->setValue(date("d-m-Y", mktime(0, 0, 0, date("m") + 1, date("d"), date("Y"))));
					} else {
						$this->view->msg = 'Xuất hiện lỗi trong quá trình thực hiện';
						$form->populate($formData);
					}
				} else {
					$form->image_url->addError('Kích thước file phải là ' . $checkImage);
					$form->populate($formData);
				}
			} else {
				$form->populate($formData);
			}
		}
	}

	public function filterAction() {
		$ssFilter = new Zend_Session_Namespace($this->_namespace);

		if ($this->_arrParam['type'] == 'search') {
			if($this->_arrParam['key'] == 1) {
				$ssFilter->keywords = trim($this->_arrParam['keywords']);
				$ssFilter->state = $this->_arrParam['state'];
			} else {
				$ssFilter->keywords = '';
				$ssFilter->state = self::ACTIVE;
			}
		}
		
		if ($this->_arrParam['type'] == 'order') {
			$ssFilter->col = $this->_arrParam['col'];
			$ssFilter->order = $this->_arrParam['by'];
		}
		
		$this->_redirect($this->_actionMain . '/index');
		$this->_helper->viewRenderer->setNoRender();
	}
	
	public function editAction() {
		$this->view->headTitle(self::EDIT_PAGE_TITLE);

		$form = new Admin_Form_Advertisement();
		$form->image_url->setRequired(false);
		$this->view->form = $form;
		$this->view->msg = '';
		
		$model = new Admin_Model_PageMapper();
		$pages = $model->fetchAll(null);
		foreach ($pages as $value) {
			$form->page_id->addMultiOption($value->getId(), $value->getPage());
		}
		
		$model = new Admin_Model_PositionMapper();
		$positions = $model->fetchAll(null);
		foreach ($positions as $value) {
			$form->vi_tri->addMultiOption($value->getId(), $value->getPosition());
		}
		
		$model = new Admin_Model_CustomerMapper();
		$customers = $model->fetchAll('trang_thai=1', 'view');
		foreach ($customers as $value) {
			$form->id_khach_hang->addMultiOption($value->getId(), $value->getTen_khach_hang());
		}
		
		$model = new Admin_Model_AdpackageMapper();
		$advPackages = $model->fetchAll('trang_thai=1', 'view');
		foreach ($advPackages as $value) {
			$form->id_goi_quang_cao->addMultiOption($value->getId(), $value->getTen_goi());
		}

		$model = new Admin_Model_AdvertisementMapper();
		$arrData = $model->fetchAll('id=' . $this->_getParam('id', 0), 'edit');
		$data = array_shift($arrData);

		if ($data != null) {
			if ($this->getRequest()->isPost()) {
				$formData = $this->getRequest()->getPost();

				if ($form->isValid($formData)) {
					$advertisement = new Admin_Model_TableColumn_Advertisement($data);
					$currentDate = date('Y-m-d H:i:s');
					
					if (is_uploaded_file($_FILES['image_url']['tmp_name'])) {
						$checkImage = $this->checkImageSize($_FILES['image_url']['tmp_name'], $form->getValue('vi_tri'));
						
						if($checkImage == '') {
							unlink(ADV_IMAGES_PATH . $advertisement->getImage_url());
							
							$upload = new Zendhlt_File_Upload();
							$newFileName = $upload->upload('image_url', ADV_IMAGES_PATH, array('task' => 'rename'));
							
							$advertisement->setImage_url($newFileName);
							$advertisement->setPage_id($form->getValue('page_id'));
							$advertisement->setVi_tri($form->getValue('vi_tri'));
							$advertisement->setId_khach_hang($form->getValue('id_khach_hang'));
							$advertisement->setId_goi_quang_cao($form->getValue('id_goi_quang_cao'));
							$advertisement->setUrl($form->getValue('url'));
							$advertisement->setUu_tien($form->getValue('uu_tien'));
							$advertisement->setNgay_het_han(date_format(date_create_from_format('d-m-Y', $form->getValue('ngay_het_han')), 'Y-m-d'));
							$advertisement->setMota($form->getValue('mota'));
							$advertisement->setNguoi_cap_nhat($this->_currentUser->id);
							$advertisement->setNgay_cap_nhat($currentDate);
							
							if ($model->save($advertisement)) {
								$this->_redirect($this->_actionMain . '/index/page/' . $this->_paginator['currentPage']);
							} else {
								$this->view->msg = 'Xuất hiện lổi trong quá trình thực hiện.';
								$form->populate($formData);
							}
						} else {
							$form->image_url->addError('Kích thước file phải là ' . $checkImage);
							$form->populate($formData);
						}
					} else {
						$advertisement->setPage_id($form->getValue('page_id'));
						$advertisement->setVi_tri($form->getValue('vi_tri'));
						$advertisement->setId_khach_hang($form->getValue('id_khach_hang'));
						$advertisement->setId_goi_quang_cao($form->getValue('id_goi_quang_cao'));
						$advertisement->setUrl($form->getValue('url'));
						$advertisement->setUu_tien($form->getValue('uu_tien'));
						$advertisement->setNgay_het_han(date_format(date_create_from_format('d-m-Y', $form->getValue('ngay_het_han')), 'Y-m-d'));
						$advertisement->setMota($form->getValue('mota'));
						$advertisement->setNguoi_cap_nhat($this->_currentUser->id);
						$advertisement->setNgay_cap_nhat($currentDate);
							
						if ($model->save($advertisement)) {
							$this->_redirect($this->_actionMain . '/index/page/' . $this->_paginator['currentPage']);
						} else {
							$this->view->msg = 'Xuất hiện lổi trong quá trình thực hiện.';
							$form->populate($formData);
						}
					}
				} else {
					$form->populate($formData);
				}
			} else {
				$data['ngay_het_han'] = date('d-m-Y', strtotime($data['ngay_het_han']));
				$form->populate($data);
			}
		} else {
			$this->view->msg = 'Dữ liệu không tồn tại trong database.';
		}
	}

	// Update trang thai ẩn|hiện
	public function deleteAction() {
		$model = new Admin_Model_AdvertisementMapper();

		if (isset($this->_arrParam['id'])) {
			$id = $this->_arrParam['id'];
		} elseif (isset($this->_arrParam['cid'])) {
			$id = $this->_arrParam['cid'];
		}

		if ($id != null) {
			$state = $this->_arrParam['delete-type'];

			if ($model->deleteItems($id, $state, $this->_currentUser->id) == false) {
				$ssFilter = new Zend_Session_Namespace($this->_namespace);
				$ssFilter->error = 1;
			}
		}

		$this->_redirect($this->_actionMain . '/index');
		$this->_helper->viewRenderer->setNoRender();
	}

	// Xoá du lieu trong database
	public function removeAction() {
		$model = new Admin_Model_AdvertisementMapper();
		$ssFilter = new Zend_Session_Namespace($this->_namespace);

		if (isset($this->_arrParam['cid'])) {
			$ids = $this->_arrParam['cid'];

			foreach ($ids as $id) {
				$arrData = $model->fetchAll("id = $id", 'edit');
				$data = array_shift($arrData);
					
				if ($data != null) {
					$advertisement = new Admin_Model_TableColumn_Advertisement($data);
				
					if ($model->removeItems($id) == false) {
						$ssFilter->error = 1;
				
					} else {
						unlink(ADV_IMAGES_PATH . $advertisement->getImage_url());
					}
				
				} else {
					$ssFilter->error = 1;
				}
			}
		}

		$this->_redirect($this->_actionMain . '/index');
		$this->_helper->viewRenderer->setNoRender();
	}
	
}
?>